package com.rongshu.view.userInfo.activity;

import android.animation.Animator;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.AnimationUtil;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.LoginUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.activity.UserHomePageActivity;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.discovery.bean.SearchAuthorResponse;
import com.rongshu.view.home.listener.OnItemMoreClickListener;
import com.rongshu.view.userInfo.adapter.ListManagementAdapter;
import com.rongshu.view.userInfo.iview.FansView;
import com.rongshu.view.userInfo.presenter.FansPresenter;
import com.rongshu.widget.BanyanDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.widget.loading.AnimatorListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.rongshu.utils.UserInfoUtils.getUserId;

public class FansActivity extends BaseActivity<FansPresenter> implements FansView, OnItemMoreClickListener {
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.layout_empty)
    RelativeLayout layout_empty;
    @BindView(R.id.empty_hint)
    TextView emptyHint;

    //manager
    private LinearLayoutManager manager = null;
    //adapter
    private ListManagementAdapter adapter = null;
    //map
    private Map<String, Object> map = null;
    private int pageIndex = 1;
    private int pageSize = 10;
    //refresh,load
    private boolean isrefresh = true;
    //关注,取消关注人的信息
    private AuthorDetailBean authorDetailBean = null;
    //取消关注使用
    private BanyanDialog banyanInputDialog = null;
    //position
    private int position = 0;
    //request
    private final int REQUEST = 0x01;

    @Override
    protected int initLayout() {
        return R.layout.activity_fans_view;
    }

    @Override
    protected void initView() {
        //set preseter
        setPresenter(new FansPresenter(this), this);
        //设置title
        txt_top_title.setText(R.string.my_fans);
        //layoutmanager
        manager = new LinearLayoutManager(this);
        //adapter
        adapter = new ListManagementAdapter(this, ListManagementAdapter.FANS);
        adapter.setHasStableIds(true);
        adapter.setOnItemChildClickListener(this);
        //recyclerview
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        //触发自动刷新
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                isrefresh = true;
                pageIndex = 1;
                refreshLayout.resetNoMoreData();
                getSetUserRelationships();
                refreshlayout.finishRefresh(2000, false);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                isrefresh = false;
                pageIndex++;
                getSetUserRelationships();
                refreshlayout.finishLoadmore(2000, false);
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {


    }

    /**
     * 取消关注dialog
     */
    private void showCancleAttention(final View view) {
        //dialog
        BanyanDialog.Builder builder = new BanyanDialog.Builder(this);
        builder.setTitle("提示");
        builder.setContent("确定要取消对此人的关注吗?");
        builder.setLeft("取消");
        builder.setRight("确定");
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                banyanInputDialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                banyanInputDialog.dismiss();
                cancelConcernWith();
                AnimationUtil.AlphaScaleShrinkAnimator(view, new AnimatorListener() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        view.animate().alpha(1).scaleX(1).scaleY(1);
                    }
                });
            }
        });
        banyanInputDialog = builder.create();
        banyanInputDialog.show();
    }


    /**
     * 获取我的主页 我的关注 1，我的粉丝 2 ,我的黑名单 3
     */
    private void getSetUserRelationships() {
        //user_id
        int user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("type", 2);
        map.put("page", pageIndex);
        map.put("pageSize", pageSize);
        presenter.getSetUserRelationships(user_id, 2,
                pageIndex, pageSize, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 取消关注
     */
    private void cancelConcernWith() {
        if (authorDetailBean == null) {
            return;
        }
        //user_id
        int user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", 0);
        map.put("user_id_to", authorDetailBean.getUser_id_to());
        presenter.cancelConcernWith(
                (int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("user_id_to"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 关注
     */
    private void concernWith() {
        if (authorDetailBean == null) {
            return;
        }
        //user_id
        int user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", 0);
        map.put("user_id_to", authorDetailBean.getUser_id_to());
        presenter.concernWith(
                (int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("user_id_to"),
                Common.encryptionSign(map));
        map.clear();
    }


    @OnClick({R.id.layout_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST:
                    if (data != null) {
                        boolean isConcern = data.getBooleanExtra(Constant.IS_COLLECT, false);
                        adapter.getAuthorDetailBeans().get(position).setIs_mutual(isConcern ? 1 : 0);
                        adapter.getAuthorDetailBeans().get(position).setIs_guanzhu(isConcern ? 1 : 0);
                        adapter.notifyItemChanged(position);
                    }
                    break;
            }
        }
    }

    /**
     * 我的粉丝数据回调
     */
    @Override
    public void onFansUser(SearchAuthorResponse response) {
        if (response == null) {
            return;
        }
        List<AuthorDetailBean> authorDetailBeans = response.getResponse();
        if (adapter != null) {
            if (isrefresh) {
                refreshLayout.finishRefresh();
                if (authorDetailBeans == null || authorDetailBeans.isEmpty()) {
                    refreshLayout.setVisibility(View.GONE);
                    layout_empty.setVisibility(View.VISIBLE);
                } else {
                    refreshLayout.setVisibility(View.VISIBLE);
                    layout_empty.setVisibility(View.GONE);
                    adapter.setAuthorDetailBeans(authorDetailBeans);
                    adapter.notifyDataSetChanged();
                }
            } else {
                if (authorDetailBeans == null || authorDetailBeans.isEmpty()) {
                    refreshLayout.finishLoadmoreWithNoMoreData();
                } else {
                    refreshLayout.finishLoadmore();
                    adapter.addAuthorDetailBeans(authorDetailBeans);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    /**
     * 关注，取消关注
     *
     * @param bean
     */
    @Override
    public void onConcernStatus(INetBean bean, boolean isConcern) {
        if (bean.getErrCode() == 0) {
            adapter.getAuthorDetailBeans().get(position).setIs_mutual(isConcern ? 1 : 0);
            adapter.getAuthorDetailBeans().get(position).setIs_guanzhu(isConcern ? 1 : 0);
            adapter.notifyDataSetChanged();
        } else {
            toast(bean.getErrMsg());
        }
    }

    @Override
    public void onItemClick(final View view, int position) {
        if (adapter != null) {
            this.position = position;
            List<AuthorDetailBean> authorDetailBeanList = adapter.getAuthorDetailBeans();
            authorDetailBean = authorDetailBeanList.get(position);
            if (authorDetailBean != null) {
                int is_mutual = authorDetailBean.getIs_mutual();
                int is_guanzhu = authorDetailBean.getIs_guanzhu();
                if (is_mutual == 1 || is_guanzhu == 1) {
                    showCancleAttention(view);
                } else {
                    concernWith();
                    AnimationUtil.AlphaScaleAnimator(view, new AnimatorListener() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            view.animate().alpha(1).scaleX(1).scaleY(1);
                        }
                    });
                }
            }
        }
    }

    /**
     * 头像点击
     *
     * @param userIdTo
     */
    @Override
    public void onUserHeaderClick(int postion, int userIdTo, boolean is_allow_browse_homepage) {
        this.position = postion;
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this);
            return;
        }
        Intent intent = null;
        if (user_id == userIdTo) {
            intent = new Intent(this, PersonDetailsActivity.class);
        } else {
            if (!is_allow_browse_homepage) {
                toast("由于对方的设置，你暂时无法浏览他的主页");
                return;
            }
            intent = new Intent(this, UserHomePageActivity.class);
            intent.putExtra(Constant.USER_ID, userIdTo);
        }
        startActivityForResult(intent, REQUEST);
    }
}
